// import { ViewController } from 'ionic-angular';
// import { Camera } from '@ionic-native/camera';
// import { File } from '@ionic-native/file';
// import { Camera } from '@ionic-native/camera';
// import { Transfer, TransferObject } from '@ionic-native/transfer';
import { Component, Input, Output, EventEmitter } from '@angular/core';
import { IonicPage, NavController, normalizeURL, ActionSheetController, ModalController, ToastController, ViewController, LoadingController, AlertController, Platform } from 'ionic-angular';
import { FileObj } from "../../model/FileObj";
import { NativeService } from "../../providers/NativeService";
import { PreviewPicturePage } from "../preview-picture/preview-picture";
import { FileService } from "../../providers/FileService";
import { GlobalData } from "../../providers/GlobalData";
// import { BasePage } from '../../pages/basePage';
import { StorageService } from './../../providers/StorageService';

/**导入外部加载组件 */
import { File } from '@ionic-native/file';
import { Transfer, TransferObject } from '@ionic-native/transfer';
import { FilePath } from '@ionic-native/file-path';
import { Camera } from '@ionic-native/camera';
import { PIC_URL } from "./../../providers/Config";
import { Crop } from '@ionic-native/crop';
declare var cordova: any;

import { ImagePicker, ImagePickerOptions } from '@ionic-native/image-picker';



/**
 * Generated class for the SelectPicturePage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */
@IonicPage()
@Component({
  selector: 'page-select-picture',
  templateUrl: 'select-picture.html',
})
export class SelectPicturePage {

  rootpath = '';

  userId: any;
  userinfo: any;
  returndata: any;
  @Input() max: number = 1;  //最多可选择多少张图片，默认为4张

  @Input() allowDelete: boolean = true;  //是否允许删除

  @Input() imgpath = '';

  @Input() classname = 'pictureadd';

  @Input() fileObjList = [];   //图片列表,与fileObjListChange形成双向数据绑定

  @Output() fileObjListChange = new EventEmitter<any>();


  lastImage: string = null;
  // newFileName: string = null;


  isChange: boolean = false;//头像是否改变标识
  avatarPath: string = './assets/img/qr_code.png';//用户默认头像
  imageBase64: string;//保存头像base64,用于上传


  constructor(private modalCtrl: ModalController,
    private alertCtrl: AlertController,
    private actionSheetCtrl: ActionSheetController,
    public loadingCtrl: LoadingController,
    public viewCtrl: ViewController,
    private fileService: FileService,
    private globalData: GlobalData,
    public navCtrl: NavController,
    private nativeService: NativeService,
    private imagePicker: ImagePicker,
    public camera: Camera,
    private crop: Crop,
    public transfer: Transfer,
    public file: File,
    public filePath: FilePath,
    public stc: StorageService,
    public platform: Platform,
    public toastCtrl: ToastController,
  ) {
    this.userinfo = this.stc.read('userinfo');
    this.userId = this.userinfo['user_id'];
    this.rootpath = PIC_URL;
    console.log(this.max);
  }

  presentActionSheet() {
    let actionSheet = this.actionSheetCtrl.create({
      title: '选择图片',
      buttons: [
        {
          text: '从图片库中选择',
          handler: () => {
            this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
            // this.uploadImage();
          }
        },
        {
          text: '使用相机',
          handler: () => {
            this.takePicture(this.camera.PictureSourceType.CAMERA);
            // this.uploadImage();
          }
        },
        {
          text: '取消',
          role: 'cancel'
        }
      ]
    });
    actionSheet.present();
  }

  //为文件生成一个新的文件名
  createFileName() {
    var d = new Date(),
      n = d.getTime(),
      newFileName = n + ".jpg"; //拼接文件名
    return newFileName;
  }
  //处理图片的路径为可以上传的路径
  public pathForImage(img) {
    if (img === null) {
      return '';
    } else {
      return normalizeURL(cordova.file.dataDirectory + img);
      // let upImg= normalizeURL(cordova.file.dataDirectory + img);
      // this.uploadImage();
      // return upImg;
    }
  }
  //将获取到的图片或者相机拍摄到的图片进行一下另存为，用于后期的图片上传使用
  //仅用于单张图片上传
  copyFileToLocalDir(namePath, currentName, newFileName) {
    this.file.copyFile(namePath, currentName, cordova.file.dataDirectory, newFileName).then(success => {
      this.lastImage = newFileName;
      if (this.lastImage != null) {
        this.crop.crop(this.pathForImage(this.lastImage), )
          .then(
            newImage => {
              this.lastImage = '';
              this.lastImage = newImage;
              console.log(this.pathForImage(this.lastImage))
              console.log("66666")
              this.pathForImage(newImage)
              console.log(this.pathForImage(newImage))
              //  this.lastImage = newImage;
              console.log(this.lastImage)
              console.log(this.pathForImage(this.lastImage))
              console.log("66666")
              this.uploadImage();
            },
            error => console.error('Error cropping image', error)
          );
        // this.uploadImage();
      }

    }, error => {
      console.log(this.toastCtrl, "存储图片到本地图库出现错误。");
    });
  }

  // private getPictureSuccess(imageBase64) {
  //   this.isChange = true;
  //   this.imageBase64 = <string>imageBase64;
  //   this.avatarPath = 'data:image/jpeg;base64,' + imageBase64;
  // }


  takePicture(sourceType) {
    const fileTransfer: TransferObject = this.transfer.create();
    //定义相机的一些参数
    var options = {
      quality: 100, //图片的质量
      sourceType: sourceType,
      saveToPhotoAlbum: false, //是否保存拍摄的照片到相册中去
      correctOrientation: true //是否纠正拍摄的照片的方向
    };

    //获取图片的方法
    this.camera.getPicture(options).then((imagePath) => {
      //特别处理 android 平台的文件路径问题
      if (this.platform.is('android') && sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) {
        this.filePath.resolveNativePath(imagePath) //获取 android 平台下的真实路径
          .then(filePath => {
            //获取正确的路径
            let correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
            //获取正确的文件名
            let currentName = imagePath.substring(imagePath.lastIndexOf('/') + 1, imagePath.lastIndexOf('?'));
            this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
          });
        /**
      * 
      */
        this.toastCtrl.create({
          message: '安卓平台' + correctPath + '+ && +' + currentName,
          duration: 3000,
          position: 'top',
        }).present();
      }
      else {
        //获取正确的路径
        var correctPath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
        //获取正确的文件名
        var currentName = imagePath.substr(imagePath.lastIndexOf('/') + 1);
        this.copyFileToLocalDir(correctPath, currentName, this.createFileName());

        /**
         * 
         */
        this.toastCtrl.create({
          message: 'IOS平台' + correctPath + '+ && +' + currentName,
          duration: 3000,
          position: 'top',
        }).present();
      }
      // this.uploadImage();
    }, (err) => {
      // super.showToast(this.toastCtrl, "选择图片出现错误，请在 App 中操作或检查相关权限。");
      /**
         * 
         */
      this.toastCtrl.create({
        message: err,
        duration: 3000,
        position: 'middle',
      }).present();
    });
    // this.uploadImage();
  }


  async uploadImage() {
    var url = 'http://192.168.1.99:7777/admin/api/uploadCommon';
    // var targetPath = this.pathForImage(this.lastImage);
    var targetPath = this.lastImage;
    var filename = this.userId + ".jpg"; //定义上传后的文件名

    //fileTransfer 上传的参数
    var options = {
      fileKey: "file",
      fileName: filename,
      httpMethod: 'post',
      chunkedMode: true,
      mimeType: "multipart/form-data",
      params: { img: targetPath }
    };
    const fileTransfer: TransferObject = this.transfer.create();

    // var loading = super.showLoading(this.loadingCtrl, "上传中...");
    var loading = this.loadingCtrl.create({
      content: "上传中...",
      //duration: 3000,
    })
    loading.present();

    // let res=await this.userservice.uploadImgAPI(targetPath);
    // console.log(res)
    //开始正式地上传
    fileTransfer.upload(targetPath, url, options).then(data => {
      console.log(data)
      this.returndata = data.response;
      let returnImg = this.returndata.toString();
      var imgobj = eval('(' + returnImg + ')');

      loading.dismiss();
      // super.showToast(this.toastCtrl, "图片上传成功。");
      this.toastCtrl.create({
        message: '图片上传成功。',
        duration: 3000,
        position: 'top',
      }).present();
      //在用户看清弹窗提示后进行页面的关闭

      setTimeout(() => {
        console.log('我是子页面的数据');
        console.log(imgobj);
        this.fileObjList = imgobj;
        this.fileObjList['flagbs'] = this.classname;
        this.imgpath = imgobj[0];
        this.returnapiimg(imgobj);
        //this.viewCtrl.dismiss(imgobj);
      }, 2000);


      // setTimeout(() => {
      //   this.viewCtrl.dismiss(imgobj);
      // }, 2000);

    }, err => {
      loading.dismiss();
      // super.showToast(this.toastCtrl, "图片上传发生错误，请重试。");
      this.toastCtrl.create({
        message: '图片上传发生错误，请重试。',
        duration: 3000,
        position: 'bottom',
      }).present();
    });
  }

  /**输出图像组件 */
  returnapiimg(event) {
    // this.fileObjListChange.emit(event);
    console.log(this.fileObjListChange.emit(event))
    console.log(12345)
  }




  /**返回上一级目录 */
  dismissCLI() {
    console.log(this.returndata);
    console.log('2222222');
    this.viewCtrl.dismiss(this.returndata);
  }


}
